import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;

public class Calcul extends UnicastRemoteObject implements CalculInterfaceMieux {

	final static char eps = ">".charAt(0);
	public String ligne;
	public String colonne;
	public int nbrePross;
	public int etape;
	public int monID;
	public Calcul(int n,int k, String a, String b) throws RemoteException {
		this.etape = 0;
		this.nbrePross = n;
		this.monID = k;
		if(a.length() < b.length())
		{
			this.ligne = b;
			this.colonne = a;
		}
		else
		{
			this.ligne = a;
			this.colonne = b;
		}

	}

	@Override
	public int[] calcul(int[] tableau, int nbreEtape) throws RemoteException {
		etape = (tableau.length-1)/2;
		if(etape < monID)
			return null;
		else
		{
			int[] output = new int[etape/nbrePross + 1];
			int gauche,dessous,diag;
			int limit = 0;
			limit = etape/nbrePross;
			if(etape % nbrePross >= monID)
				limit++;

			for(int k= 0; k<limit; k++)
			{
				gauche = tableau[2*(monID-1) + 2*nbrePross*k];
				diag = tableau[2*(monID-1) + 2*nbrePross*k + 1];
				dessous = tableau[2*(monID-1) + 2*nbrePross*k + 2];

				output[k]= calculValeur(gauche,diag,dessous, nbreEtape, k);
			}
			return output;
		}
	}

	public static int min(int a, int b, int c) {
		return Math.min(Math.min(a, b), c);
	}

	public static int cost(char a, char b) {
		if (a == b)
			return 0;
		return 1;
	}

	private int calculValeur(int gauche, int diag, int dessous, int nbreEtapes, int caseDuTableau) {
		int i = 0;
		int j = 0;
		int nbreEtape = nbreEtapes - 1;
		if(nbreEtapes <= colonne.length())
		{
			i = nbrePross*caseDuTableau + monID;
		}
		else if (nbreEtapes < ligne.length())
		{
			i = nbrePross*caseDuTableau + monID + (nbreEtapes - colonne.length());
		} else {
			i = nbrePross*caseDuTableau + monID + (nbreEtapes - colonne.length());
		}

		j = nbreEtape - i+1;

		int result = min(gauche + cost(ligne.charAt(i -1), eps), dessous
				+ cost(colonne.charAt(j - 1), eps),
				diag + cost(ligne.charAt(i), colonne.charAt(j)));

		return result;

	}
}
